﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using AutoMapper;
using HT.Future.Application;
using HT.Future.Common;
using HT.Future.Entities;
using HT.Future.IService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;

namespace HT.Future.TxApi.Controllers
{
    [ApiVersion("1.0")]
    //[Authorize]
    [Route("api/[controller]")]
    public class OrganizationController : BaseController
    {
        private readonly IOrganizationService _service;

        public OrganizationController(IMapper mapper, IOrganizationService service) : base(mapper)
        {
            this._service = service;
        }

        /// <summary>
        /// 导入组织架构
        /// </summary>
        /// <returns></returns>
        [HttpPost("import")]
        public async Task<ApiResult> ImportOrganization()
        {
            var file = Request.Form.Files[0];
            var name = file.FileName.ToLower();
            if (!name.EndsWith(".xlsx"))
            {
                return new ApiResult(false, ApiResultStatusCode.LogicError, "请上传.xlsx文件");
            }
            var stream = file.OpenReadStream();
            await _service.ImportOrganizationAsync(stream);
            await _service.ImportUserAsync(stream);
            return new ApiResult(true, ApiResultStatusCode.Success, "导入成功");
        }

        /// <summary>
        /// 获取指定部门下的直接子部门
        /// </summary>
        /// <param name="id"></param>
        /// <param name="_user"></param>
        /// <returns></returns>
        [HttpGet("department/{id}")]
        public async Task<ApiResult<object>> GetDepartment(int id, [FromServices] IUserService _user)
        {
            //var list = await _service.Table.ToListAsync();
            //return list.FirstOrDefault(a => a.Id == 1);
            var department = await _service.GetChildsAsync(id);
            var group = await _user.TableNoTracking
                .Where(a => a.DepartmentObjectFullId.StartsWith(department.FullObjectId))
                .GroupBy(a => a.DepartmentObjectFullId)
                .Select(a => new { count = a.Count(), id = a.Key })
                .ToListAsync();
            return new
            {
                id = department.Id,
                name = department.Name,
                children = department.Departments.Select(a =>
                {
                    return new
                    {
                        id = a.Id,
                        name = a.Name,
                        type = "department",
                        count = group.Where(b => b.id.StartsWith(a.FullObjectId)).Sum(a => a.count),
                        leaf = a.Departments?.Count == 0,
                        sort = a.Sort
                    };
                })
                .OrderBy(a => a.sort)
                //.Concat(department.Users.Select(a => new
                //{
                //    id = a.Id,
                //    name = a.FullName,
                //    type = "user",
                //    leaf = true
                //})),
            };
        }

        /// <summary>
        /// 获取部门下的员工（包含下级单位的员工）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("department/users/{id}")]
        public async Task<ApiResult<List<User>>> GetUsers(int id)
        {
            return await _service.GetChildUsersAsync(id);
        }

        /// <summary>
        /// 获取公司信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("company")]
        public async Task<ApiResult<Department>> GetFullCompany()
        {
            var list = await _service.Table.ToListAsync();
            var company = list.First(a => a.Id == 1);
            return company;
        }

        /// <summary>
        /// 获取部门详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("departmentInfo/{id}")]
        public async Task<ApiResult<Department>> GetDepartmentDetail(int id)
        {
            return await _service.Table.FirstOrDefaultAsync(a => a.Id == id);
        }

        /// <summary>
        /// 更新部门信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="department"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ApiResult<Department>> Update(int id, [FromBody] Department department)
        {
            return await _service.UpdateAsync(department);
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="department"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<Department>> AddDepartment([FromBody] Department department)
        {
            var entity = await _service.CreateDepartmentAsync(department);
            return entity;
        }

        /// <summary>
        /// 获取组织下的最大排序码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("maxSort/{id}")]
        public async Task<int> ChildrenMaxSort(int id)
        {
            return await _service.ChildrenMaxSortAsync(id);
        }

        /// <summary>
        /// 获取组织架构
        /// </summary>
        /// <returns></returns>
        [HttpGet("excel")]
        public async Task<FileResult> Organization()
        {
            var file = await _service.GetOrganizationExcelAsync();
            return File(file, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"组织架构-{DateTime.Now:yyyyMMddHHmmss}.xlsx", true);
        }

        /// <summary>
        /// 导出部门下的所有员工
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("deptUsers/{id}")]
        public async Task<FileResult> ExportDepartmentUser(int id)
        {
            var file = await _service.GetDepartmentUsersToExcelAsync(id);
            var dept = await _service.GetByIdAsync(id);
            return File(file, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"{dept.Name}.xlsx", true);
        }

        /// <summary>
        /// 导出所有用户
        /// </summary>
        /// <returns></returns>
        [HttpGet("users")]
        public async Task<FileResult> ExportAllUsers()
        {
            var file = await _service.GetAllUsersToExcelAsync();
            return File(file, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"人员信息.xlsx", true);
        }
    }
}


